# -*- coding: utf-8 -*-
#线程学习
import time
#引入线程模块
import threading
def sing():
    print('singing')
    time.sleep(2)#休眠2秒
    print('sing done')

def dance():
    print('dance')
    time.sleep(2)#休眠2秒
    print('dance done')
#线程类型参数1、target：执行的任务名，2、args：以元组的形式给线程传参，3、kwargs：以字典的形式给线程传参
a = 0
b = 10000000
lock = threading.Lock()
def add1():
    lock.acquire()
    global a
    for i in range(b):
        a += 1
    print('add1 a=',a)
    lock.release()
def add2():
    lock.acquire()
    global a
    for i in range(b):
        a += 1
    print('add2 a=',a)
    lock.release()


if __name__ == '__main__':
    # 创建子线程
    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)
    #守护线程，必须在线程启动之前：主线程结束之后子线程也会跟着结束
    t1.daemon = True
    t2.daemon = True
    #启动子线程
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    #获取线程名字
    print(t1.name)
    print(t2.name)
    t1.name ='sub1'
    print(t1.name)
    t2.name = 'sub2'
    print(t2.name)
    #阻塞主线程join：必须在start后面，起到暂停主线程的作用，等待子线程执行结束后在执行主线程
    print('every thing done')
    #线程执行是无序的
    #线程同步的两种方式
    #2、互斥锁
    t3 = threading.Thread(target=add1)
    t4 = threading.Thread(target=add2)
    t3.start()
    #1、join
    #t3.join()
    t4.start()
    #1、join
   # t4.join()
